-- Autocmds are automatically loaded on the VeryLazy event
-- Default autocmds that are always set: https://github.com/LazyVim/LazyVim/blob/main/lua/lazyvim/config/autocmds.lua
--
-- Add any additional autocmds here
-- with `vim.api.nvim_create_autocmd`
--
-- Or remove existing autocmds by their group name (which is prefixed with `lazyvim_` for the defaults)
-- e.g. vim.api.nvim_del_augroup_by_name("lazyvim_wrap_spell")
if vim.fn.has("mac") == 1 then
  -- curl -Ls -o im-se https://raw.githubusercontent.com/daipeihust/im-select/master/macOS/out/intel/im-select
  vim.api.nvim_create_autocmd({ "InsertEnter", "InsertLeave", "TermEnter" }, {
    pattern = "*",
    callback = function()
      vim.fn.system("~/bin/im-select com.apple.keylayout.ABC")
    end,
  })
end
-- 保存插入模式退出前的输入法状态（可选）
if vim.fn.has("linux") == 1 then
  local fcitx_state = 1
  -- 进入插入模式时，恢复之前的输入法状态（或强制打开中文）
  vim.api.nvim_create_autocmd("InsertEnter","TermEnter","TermLeave","InsertLeave", {
    pattern = "*",
    callback = function()
      -- 方式1：恢复退出插入模式前的状态
      os.execute("fcitx5-remote -s " .. fcitx_state)

      -- 方式2：强制打开中文（根据需求选择）
      -- os.execute("fcitx5-remote -o")
    end,
  })

  -- 退出插入模式时，切回英文并保存当前状态
  vim.api.nvim_create_autocmd("InsertLeave", {
    pattern = "*",
    callback = function()
      -- 获取当前输入法状态并保存
      local handle = io.popen("fcitx5-remote")
      if handle then
        fcitx_state = handle:read("*a"):gsub("%s+", "") -- 去除换行符
        handle:close()
      end
      -- 强制切英文
      os.execute("fcitx5-remote -c")
    end,
  })

  -- 切换到命令行模式（:）时切英文
  vim.api.nvim_create_autocmd("CmdlineEnter", {
    pattern = "*",
    callback = function()
      os.execute("fcitx5-remote -c")
    end,
  })
end
